// 1 创建构造函数
function Person(id, name, age) {
  this.age = age
  this.name = name
  this.id = id
  this.info = function () {
    console.log(`{ name: ${this.name}, age: ${this.age}, id: ${this.id} }`)
  }
}
// 2 给原型对象添加show方法
Person.prototype.tag = '<h1>true</h1>'
Person.prototype.show = function () {
  return `{ name: ${this.name}, age: ${this.age}, id: ${this.id} }`
}

// 3 创建对象
let person = new Person(1, 'wenddy', 20)
console.log(person)
let box = document.querySelector('.box')

// 4 实例共享原型属性和方法
let person1 = new Person(2, 'tom', 21)
person1.__proto__.tag = '<h1>false</h1>'
box.innerHTML = person.tag + `<div>${person.show()}</div>`

// 5 使用原型方法实现字符串去空格
String.prototype.removeSpace = function () {
  // 此处的this是函数removeSpace的调用者
  return this.replace(/\s/g, '')
}

let str = ' hello web32 '
str = str.removeSpace()
console.log('$' + str + '$') // $helloweb32$
let st1 = ' 今天学 习 面 向 对象 '
console.log('$' + st1.removeSpace() + '$')

// 6 使用原型格式化日期
Date.prototype.formatDate = function () {
  // 此处的this是函数formatDate的调用者
  const year = this.getFullYear()
  const month = this.getMonth() + 1
  const day = this.getDate()
  const hour = this.getHours()
  const minute = this.getMinutes()
  const second = this.getSeconds()
  return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

let date = new Date()
console.log(date.formatDate()) // 2022-11-10 17:18:52
let date1 = new Date('2011-12-21 08:09:10')
console.log(date1.formatDate()) // 2011-12-21 08:09:10
